package com.bdyc.filter;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;

public class CharacterEncodingFilter implements Filter{
	private String encoding = "utf-8";//默认编码
	
	public void init(FilterConfig filterConfig) throws ServletException {
		encoding = filterConfig.getInitParameter("encoding");
	}
	
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse resp = (HttpServletResponse)response;
		
		//处理post请求乱码
		req.setCharacterEncoding(encoding);
		resp.setCharacterEncoding(encoding);
		
		chain.doFilter(new MyHttpServletRequest(req), resp);//放行
	}

	public void destroy() {
		
	}

}

/*
 * 万能编码过滤器：
 */
class MyHttpServletRequest extends HttpServletRequestWrapper{

	//存放被扩展的对象
	private HttpServletRequest req;
	public MyHttpServletRequest(HttpServletRequest request) {
		super(request);
		this.req = request;
	}

	//扩展之后方法：
	@Override
	public String getParameter(String name) {
		
		try {
			String value = req.getParameter(name);
			if(value == null){//如果为空
				return value;
			}
			//metdhod： type
			if(!"get".equalsIgnoreCase(req.getMethod())){//如果是get请求
				return value;
			}
			return new String(value.getBytes("iso8859-1"),req.getCharacterEncoding());
		
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
}
